<template>
  <div class="product-config">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <h2>产品配置管理</h2>
          <div class="header-actions">
            <el-dropdown @command="handleImportCommand">
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                导入数据
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="downloadTemplate">
                    <el-icon><Download /></el-icon>
                    下载模板
                  </el-dropdown-item>
                  <el-dropdown-item command="importExcel">
                    <el-icon><Upload /></el-icon>
                    导入Excel
                  </el-dropdown-item>
                  <el-dropdown-item command="importCSV">
                    <el-icon><Document /></el-icon>
                    导入CSV
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="success" @click="handleAddClick">
              <el-icon><Plus /></el-icon>
              添加产品
            </el-button>
            <el-button 
              type="primary" 
              @click="handleRemoteConfig"
              :loading="syncing"
            >
              <el-icon><Connection /></el-icon>
              远程配置
            </el-button>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table 
          :data="paginatedProducts" 
          border
          style="width: 100%"
          height="400"
          v-loading="isTableLoading"
        >
          <el-table-column label="产品编码" prop="productCode" min-width="150" />
          <el-table-column label="产品名称" prop="productName" min-width="200" />
          <el-table-column label="关键代码" prop="keyCode" min-width="120" />

          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[20, 30, 40, 50]"
            :total="productStore.products.length"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 扫码规则配置卡片 -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <h2>扫码规则配置</h2>
          <div class="header-actions">
            <el-button type="primary" @click="handleSaveRule">
              <el-icon><Check /></el-icon>
              保存规则
            </el-button>
          </div>
        </div>
      </template>

      <el-form :model="ruleForm" label-width="120px">
        <el-form-item label="规则启用状态">
          <el-switch v-model="ruleForm.enabled" />
          <div class="form-tip">启用后将对扫码内容进行格式验证</div>
        </el-form-item>
        <el-form-item label="正则表达式">
          <el-input 
            v-model="ruleForm.pattern"
            placeholder="请输入正则表达式，：.{10,}"
          >
            <template #append>
              <el-button @click="testRule">测试规则</el-button>
            </template>
          </el-input>
          <div class="form-tip">例如：.{10,} 表示至少10个字符</div>
        </el-form-item>
        <el-form-item label="规则说明">
          <el-input 
            v-model="ruleForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入规则说明，例如：扫码内容至少需要10个字符"
          />
          <div class="form-tip">此说明将显示在扫码失败时的提示信息中</div>
        </el-form-item>
      </el-form>

      <div class="rule-test" v-if="showTestInput">
        <el-divider>规则测试</el-divider>
        <el-input
          v-model="testInput"
          placeholder="请输入测试内容"
          @input="handleTestInput"
        >
          <template #append>
            <el-tag :type="testResult ? 'success' : 'danger'" size="small">
              {{ testResult ? '通过' : '不通过' }}
            </el-tag>
          </template>
        </el-input>
      </div>
    </el-card>

    <!-- 添加产品对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="加产品"
      width="500px"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="产品编码" prop="productCode">
          <el-input v-model="addForm.productCode" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="addForm.productName" />
        </el-form-item>
        <el-form-item label="关键代码" prop="keyCode">
          <el-input v-model="addForm.keyCode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 远程配置对话框 -->
    <el-dialog
      v-model="showRemoteDialog"
      title="远程Excel配置"
      width="600px"
    >
      <el-form
        ref="remoteFormRef"
        :model="remoteForm"
        :rules="remoteFormRules"
        label-width="100px"
      >
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="remoteForm.name" placeholder="例如：生产部产品配置" />
        </el-form-item>
        <el-form-item label="Excel地址" prop="url">
          <el-input v-model="remoteForm.url" placeholder="请输入共享文件夹中的Excel文件地址" />
          <div class="form-tip">支持本地共享文件路径，例如：\\192.168.1.100\share\products.xlsx</div>
        </el-form-item>
        <el-form-item label="工作表名称" prop="sheetName">
          <el-input v-model="remoteForm.sheetName" placeholder="留空则使用第一个工作表" />
        </el-form-item>
        <el-form-item label="启用自动同步" prop="enabled">
          <el-switch v-model="remoteForm.enabled" />
          <div class="form-tip">启用后每5分钟自动同步一次</div>
        </el-form-item>
      </el-form>

      <div v-if="productStore.lastSyncTime" class="sync-info">
        上次同步时间：{{ formatDate(productStore.lastSyncTime) }}
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRemoteDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSaveRemoteConfig"
            :loading="saving"
          >保存配置</el-button>
          <el-button 
            type="success" 
            @click="handleSyncNow"
            :loading="syncing"
          >立即同步</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Upload, 
  Download, 
  Document, 
  Plus, 
  Delete, 
  ArrowDown, 
  Connection, 
  Check 
} from '@element-plus/icons-vue'
import { useProductStore } from '../stores/product'
import { useScanStore } from '../stores/scan'
import type { Product, RemoteExcelConfig, ScanRuleConfig } from '../types'
import * as XLSX from 'xlsx'
import dayjs from 'dayjs'

const productStore = useProductStore()
const scanStore = useScanStore()

// 添加产品相关
const showAddDialog = ref(false)
const addFormRef = ref()
const addForm = ref({
  productCode: '',
  productName: '',
  keyCode: ''
})

const addFormRules = {
  productCode: [
    { required: true, message: '请输入产品编码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  keyCode: [
    { required: true, message: '请输入关键代码', trigger: 'blur' }
  ]
}

// 远程配置相关
const showRemoteDialog = ref(false)
const remoteFormRef = ref()
const saving = ref(false)
const syncing = ref(false)

const remoteForm = ref<RemoteExcelConfig>({
  name: '',
  url: '',
  sheetName: '',
  enabled: false
})

const remoteFormRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入Excel文件地址', trigger: 'blur' }
  ]
}

// 处理添加产品
const handleAddClick = () => {
  showAddDialog.value = true
  addForm.value = {
    productCode: '',
    productName: '',
    keyCode: ''
  }
}

const handleAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    await productStore.addProduct(addForm.value)
    ElMessage.success('添加成功')
    showAddDialog.value = false
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

// 处理远程配置
const handleRemoteConfig = () => {
  showRemoteDialog.value = true
  // 如果已有配置，则填充表单
  if (productStore.remoteConfig) {
    remoteForm.value = { ...productStore.remoteConfig }
  }
}

const handleSaveRemoteConfig = async () => {
  if (!remoteFormRef.value) return

  try {
    await remoteFormRef.value.validate()
    saving.value = true
    await productStore.saveRemoteConfig(remoteForm.value)
    ElMessage.success('配置保存成功')
    showRemoteDialog.value = false
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    saving.value = false
  }
}

const handleSyncNow = async () => {
  if (!productStore.remoteConfig?.url) {
    ElMessage.warning('请先配置远程Excel地址')
    return
  }

  try {
    syncing.value = true
    await productStore.syncRemoteData()
    ElMessage.success('同步成功')
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    syncing.value = false
  }
}

// 处理删除产品
const handleDelete = async (row: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品"${row.productName}"吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await productStore.deleteProduct(row.id)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const isTableLoading = ref(false)

const paginatedProducts = computed(() => {
  // 开始加载
  isTableLoading.value = true
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const result = productStore.products.slice(start, end)
  
  // 完成加载
  nextTick(() => {
    isTableLoading.value = false
  })
  
  return result
})

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  isTableLoading.value = true
  
  // 延迟释放加载状态
  nextTick(() => {
    setTimeout(() => {
      isTableLoading.value = false
    }, 300)
  })
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  isTableLoading.value = true
  
  // 延迟释放加载状态
  nextTick(() => {
    setTimeout(() => {
      isTableLoading.value = false
    }, 300)
  })
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 导入相关
const handleImportCommand = (command: string) => {
  switch (command) {
    case 'downloadTemplate':
      downloadTemplate()
      break
    case 'importExcel':
      importExcel()
      break
    case 'importCSV':
      importCSV()
      break
  }
}

const downloadTemplate = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new()
  
  // 创建工作表数据
  const wsData = [
    ['格式说明：请按照以下格式填写产品信息（此行不要删除）'],
    ['产品编码', '产品名称', '关键代码'],
    ['TEST001', '测试产品1', 'KEY001'],
    ['TEST002', '测试产品2', 'KEY002']
  ]
  
  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(wsData)
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '产品导入模板')
  
  // 导出文件
  XLSX.writeFile(wb, '产品导入模板.xlsx')
}

const importExcel = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = async (e: Event) => {
    const target = e.target as HTMLInputElement
    if (!target.files?.length) return
    
    const file = target.files[0]
    const reader = new FileReader()
    
    reader.onload = async (e) => {
      try {
        const data = new Uint8Array(e.target?.result as ArrayBuffer)
        const workbook = XLSX.read(data, { type: 'array' })
        
        // 获取第一个工作表
        const worksheet = workbook.Sheets[workbook.SheetNames[0]]
        const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as any[]
        
        // 导入数据
        for (let i = 2; i < rows.length; i++) {
          const row = rows[i]
          if (!row || row.length < 3) continue
          
          const [productCode, productName, keyCode] = row
          
          // 跳过空行和说明行
          if (!productCode || !productName || !keyCode) continue
          if (productCode.startsWith('格式说明')) continue
          
          try {
            await productStore.addProduct({
              productCode,
              productName,
              keyCode
            })
          } catch (error) {
            console.error(`导入第${i+1}行失败:`, error)
          }
        }
        
        ElMessage.success('导入成功')
      } catch (error) {
        ElMessage.error('文件解析失败')
      }
    }
    
    reader.onerror = () => {
      ElMessage.error('文件读取失败')
    }
    
    reader.readAsArrayBuffer(file)
  }
  
  input.click()
}

const importCSV = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.csv'
  input.onchange = async (e: Event) => {
    const target = e.target as HTMLInputElement
    if (!target.files?.length) return
    
    const file = target.files[0]
    const reader = new FileReader()
    
    reader.onload = async (e) => {
      try {
        const text = e.target?.result as string
        const rows = text.split('\n').map(row => row.split(','))
        
        // 导入数据
        for (let i = 1; i < rows.length; i++) {
          const row = rows[i]
          if (!row || row.length < 3) continue
          
          const [productCode, productName, keyCode] = row
          
          // 跳过空行
          if (!productCode || !productName || !keyCode) continue
          
          try {
            await productStore.addProduct({
              productCode: productCode.trim(),
              productName: productName.trim(),
              keyCode: keyCode.trim()
            })
          } catch (error) {
            console.error(`导入第${i+1}行失败:`, error)
          }
        }
        
        ElMessage.success('导入成功')
      } catch (error) {
        ElMessage.error('文件解析失败')
      }
    }
    
    reader.onerror = () => {
      ElMessage.error('文件读取失败')
    }
    
    reader.readAsText(file)
  }
  
  input.click()
}

// 扫码规则配置相关
const ruleForm = reactive<ScanRuleConfig>({
  pattern: scanStore.scanRule.pattern,
  description: scanStore.scanRule.description,
  enabled: scanStore.scanRule.enabled
})

const showTestInput = ref(false)
const testInput = ref('')
const testResult = ref(false)

// 测试规则
const testRule = () => {
  if (!ruleForm.pattern.trim()) {
    ElMessage.warning('请先输入正则表达式')
    return
  }
  
  try {
    new RegExp(ruleForm.pattern)
    showTestInput.value = true
    testInput.value = ''
    testResult.value = false
  } catch (error) {
    ElMessage.error('正则表达式格式无效')
  }
}

// 处理测试输入
const handleTestInput = () => {
  if (!testInput.value || !ruleForm.pattern) {
    testResult.value = false
    return
  }

  try {
    const regex = new RegExp(ruleForm.pattern)
    testResult.value = regex.test(testInput.value)
  } catch (error) {
    testResult.value = false
  }
}

// 保存规则
const handleSaveRule = () => {
  if (!ruleForm.pattern.trim()) {
    ElMessage.warning('请输入正则表达式')
    return
  }

  if (!ruleForm.description.trim()) {
    ElMessage.warning('请输规则说明')
    return
  }

  try {
    // 测试正则表达式是否有效
    new RegExp(ruleForm.pattern)
    
    scanStore.updateScanRule({
      pattern: ruleForm.pattern.trim(),
      description: ruleForm.description.trim(),
      enabled: ruleForm.enabled
    })
    
    ElMessage.success('规则保存成功')
    showTestInput.value = false
  } catch (error) {
    ElMessage.error('正则表达式格式无效')
  }
}

// 组件卸载时清理定时器
onUnmounted(() => {
  productStore.stopAutoSync()
})
</script>

<style scoped>
.product-config {
  padding: 20px;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
  line-height: 1.4;
}

.rule-test {
  margin-top: 20px;
}

.el-divider {
  margin: 16px 0;
}

.table-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

/* 优化表格样式 */
:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  border-radius: 4px;
  border: 1px solid var(--el-table-border-color);
}

:deep(.el-table__header-wrapper) {
  border-radius: 4px 4px 0 0;
  overflow: hidden;
}

:deep(.el-table__body-wrapper) {
  border-radius: 0 0 4px 4px;
  overflow: hidden;
}

/* 优化滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: var(--el-border-color-darker);
  border-radius: 4px;
  border: 2px solid transparent;
  background-clip: padding-box;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: var(--el-border-color-light);
  border-radius: 4px;
}

/* 确保固定列的阴影效果正确 */
:deep(.el-table__fixed-right) {
  height: 100% !important;
  bottom: 0 !important;
}

:deep(.el-table__fixed-left) {
  height: 100% !important;
  bottom: 0 !important;
}

/* 确保表格内容垂直居中 */
:deep(.el-table__cell) {
  vertical-align: middle;
}

/* 下拉菜单项样式 */
.el-dropdown-menu__item {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 按钮图标样式 */
:deep(.el-button .el-icon) {
  margin-right: 4px;
}

:deep(.el-button .el-icon--right) {
  margin-right: 0;
  margin-left: 4px;
}

/* 上传按钮样式 */
:deep(.el-upload) {
  margin-right: 10px;
}

/* 按钮样式 */
.el-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 表格单元格样式 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

:deep(.el-dialog__footer) {
  padding-top: 0;
}
</style> 